#packages
need = c(
  "dplyr",       #data structuring
  "scales",      #rescale
  "tidyr"        #drop_na
)
#load & install packages if necessary
have = need %in% rownames(installed.packages())
if ( any(!have) ) { install.packages( need[!have] ) }
pack <- lapply(need, library, character.only = TRUE)
rm(have,need,pack)

# Load data
load("D:/POBE/datasets/anes_Immig.Rdata")
load("D:/POBE/datasets/gss_Dat.Rdata")

# Ideological self-ID
gss_Polviews <- gss_Dat %>%
  select(partyid, genPew, genDec, ageGroup, year, polviews, white, protcattend, college, cohort) %>%
  drop_na() %>%
  droplevels() %>%
  mutate(across(c(polviews, partyid), ~rescale(., to = c(0, 1))))

gss_Polviews$att <- gss_Polviews$polviews

#social welfare
gss_Swelfare <- gss_Dat %>%
  select(partyid, genPew, genDec, ageGroup, year, eqwlth, natsoc, starts_with("help"), white, protcattend, college, cohort) %>%
  drop_na() %>%
  droplevels() %>%
  mutate(across(c(starts_with('help'), eqwlth, natsoc, partyid), ~rescale(., to = c(0, 1))))

gss_Swelfare$att <- rowMeans(select(gss_Swelfare, starts_with('help'), eqwlth, natsoc))

#race and gender
gss_Racgender <- gss_Dat %>%
  select(partyid, genPew, genDec, ageGroup, year, helpblk, starts_with("fe"), white, protcattend, college, cohort) %>%
  drop_na() %>%
  droplevels() %>%
  mutate(across(c(partyid, starts_with("fe"), helpblk), ~rescale(., to = c(0, 1)))) %>%
  mutate(feSum = rowMeans(select(., starts_with('fe'))))

gss_Racgender$att <- rowMeans(select(gss_Racgender, feSum, helpblk))

#culture and morality
gss_Cultmoral <- gss_Dat %>%
  select(partyid, genPew, genDec, ageGroup, year, partyid, starts_with("ab"), divlaw, premars, white, protcattend, college, cohort) %>%
  drop_na() %>%
  droplevels() %>%
  mutate(across(c(partyid, starts_with("ab"), divlaw, premars), ~rescale(., to = c(0, 1)))) %>%
  mutate(abSum = rowMeans(select(., starts_with("ab"))))

gss_Cultmoral$att <- rowMeans(select(gss_Cultmoral, abSum, divlaw, premars))

gss_Polviews  <- as.data.frame(gss_Polviews)
gss_Swelfare  <- as.data.frame(gss_Swelfare)
gss_Racgender <- as.data.frame(gss_Racgender)
gss_Cultmoral <- as.data.frame(gss_Cultmoral)
anes_Immig    <- as.data.frame(anes_Immig)

anes_Immig$year <- factor(anes_Immig$year, levels = c("2020", "1992", "1994", "1996", "1998", "2004", "2008", "2012", "2016"))
